package com.tongtech.proxy.core.server;

import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;

public class SSLfactorctinv {
    private SSLSocketFactory buildSslSocketFactory(String p12FilePath, String password) {

        File certificate = new File(p12FilePath);
        if (!certificate.exists() || certificate.isDirectory())
            throw new RuntimeException("指定证书路径错误！");

        try {
            // 从 p12 文件加载证书和私钥
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            InputStream inputStream = new FileInputStream(certificate.getAbsolutePath());
            keyStore.load(inputStream, password.toCharArray());

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password.toCharArray());

            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // 创建 SSL 上下文并设置证书
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new SecureRandom());

            return sslContext.getSocketFactory();

        } catch (Exception e) {
            throw new RuntimeException("载入证书错误：" + e.getMessage());
        }
    }
}
